package cn.crawler.framework.filter;

import cn.crawler.framework.util.TLManager;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.View;
import org.nutz.mvc.filter.CrossOriginFilter;
import org.nutz.mvc.impl.processor.AbstractProcessor;

/**
 * 为paramFilter设置全局生效
 * 绑定actionContext获取rpc过程中出现的异常
 */
public class NutFilterProcessor extends AbstractProcessor {
    private ParamFilter paramFilter;
    private CrossOriginFilter crossOriginFilter;
    private IPTablesFilter ipTablesFilter;
    private DebugFilter debugFilter;

    @Override
    public void init(NutConfig config, ActionInfo ai) throws Throwable {
        paramFilter = config.getIoc().get(ParamFilter.class);
        crossOriginFilter = config.getIoc().get(CrossOriginTokenFilter.class);
        ipTablesFilter = config.getIoc().get(IPTablesFilter.class);
        debugFilter = config.getIoc().get(DebugFilter.class);
    }

    @Override
    public void process(ActionContext ac) throws Throwable {
        //设ac全局生效以用于自定义业务异常处理器
        TLManager.set(ac);
        View view = getView(ac);
        if (null != view) {
            ac.setMethodReturn(view);
            renderView(ac);
            return;
        }
        doNext(ac);
    }

    private View getView(ActionContext ac) {
        //允许跨域
        View view = crossOriginFilter.match(ac);
        if (view == null) {
            //ip禁用否
            view = ipTablesFilter.match(ac);
            if (view == null) {
                //debug专用接口验证
                view = debugFilter.match(ac);
            }
            if (view == null) {
                //参数正常否
                view = paramFilter.match(ac);
            }
        }
        return view;
    }
}
